package com.goktech.controller;

import com.goktech.entity.Admin;
import com.goktech.entity.User;
import com.goktech.service.AdminService;
import com.goktech.service.UserService;
import com.goktech.util.javaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @ClassName loginController
 * @Description TODO
 * @Author 邱华英
 * @Date 2022/10/5 9:30
 * @Version 1.0
 */

@Controller
@RequestMapping("/login")
public class loginController {

    @Autowired
    User u;

    @Autowired
    Admin a;

    @Autowired
    UserService userService;

    @Autowired
    AdminService adminService;

    @RequestMapping("/user")
    public String login(String zhanghao,String password,String task,HttpServletRequest request){
        System.out.println("1");
        if("user".equals(task)){
            u.setZhanghao(zhanghao);
            u.setPassword(javaUtil.getResult(password));

            User byUser = userService.findByZhanghaoPassword(u);
            System.out.println(byUser);
            if(byUser != null){
                HttpSession session = request.getSession();
                session.setAttribute("username",byUser.getUserName());
                session.setAttribute("zhanghao",byUser.getZhanghao());
                return "forward:/user/";
            }else{
                System.out.println("2");
                return "redirect:../index.jsp";
            }
        }else if("admin".equals(task)){
            a.setAzhanghao(zhanghao);
            a.setApassword(javaUtil.getResult(password));

            Admin byAdmin = adminService.findByAdmin(a);

            if(byAdmin != null){
                HttpSession session = request.getSession();
                session.setAttribute("admin",byAdmin.getAdminName());
                session.setAttribute("Azhanghao",byAdmin.getAzhanghao());
                System.out.println("byAdmin.getAzhanghao:"+byAdmin.getAzhanghao());
                System.out.println("byadmin:"+byAdmin);
                return "redirect:/admin/";
            }
        }
        return "redirect:../index.jsp";
    }


    @RequestMapping("/quit")
    public String quit(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.invalidate();
        return "redirect:../index.jsp";
    }
}
